package com.sgb.kjwl.viewmodel.carrierDemand;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import androidx.databinding.ObservableField;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.amap.api.maps.model.LatLng;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.ProListEntity;
import com.sgb.kjwl.model.entity.transport.CarFilterEntity;
import com.sgb.kjwl.model.entity.transport.CarriageInfo;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.GoodsSourceFilterEntity;
import com.sgb.kjwl.model.entity.transport.GoodsSourceLocationEntity;
import com.sgb.kjwl.model.entity.transport.MapCarEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.utils.LocationUtil;
import com.sgb.kjwl.view.ui.fragment.home.FindCarMapAndListFragment;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FindCarMapAndListModel extends AndroidViewModel {
    private FindCarMapAndListFragment fragment;
    public ObservableField<String> messageNum = new ObservableField<>("");
    public ObservableField<GoodsSourceFilterEntity> filterEntity = new ObservableField<>(new GoodsSourceFilterEntity());
    public ObservableField<GoodsSourceLocationEntity> sendLocation = new ObservableField<>(new GoodsSourceLocationEntity());
    public ObservableField<GoodsSourceLocationEntity> purposeLocation = new ObservableField<>(new GoodsSourceLocationEntity());
    public ObservableField<GoodsInfoTypeEntity3> carType = new ObservableField<>(new GoodsInfoTypeEntity3());
    public ObservableField<GoodsInfoTypeEntity3> carLength = new ObservableField<>(new GoodsInfoTypeEntity3());
    public ObservableField<GoodsInfoTypeEntity3> findGoodsType = new ObservableField<>(new GoodsInfoTypeEntity3());
    public MutableLiveData<CarFilterEntity> ldLaction = new MutableLiveData<>();
    public MutableLiveData<LatLng> ldLatLng = new MutableLiveData<>();
    public MutableLiveData<List<MapCarEntity>> ldCars = new MutableLiveData<>();
    public String radius;
    public int pageSize = 10;

    public FindCarMapAndListModel(Application application) {
        super(application);
        ldLaction.setValue(new CarFilterEntity());
    }

    public void setFragment(FindCarMapAndListFragment fragment) {
        this.fragment = fragment;
    }

    /**
     * 获取列表页承运列表数据
     */
    public void getListCar(int pageNum, String keyWord) {
        Map map = new HashMap();
        map.put("page", pageNum);
        map.put("limit", pageSize);
        if (LocationUtil.isOpenLocation(fragment.getActivity()) && LocationUtil.currentLocationIsValid()) {
            map.put("longitude", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, ""));
            map.put("latitude", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, ""));
        } else {
            // TODO: 2021/12/15 没开启定位逻辑处理
        }

        if (null != sendLocation.get()) {
            if (TextUtils.isEmpty(sendLocation.get().getProvinceNo())) {
                map.put("provinceNo", "");
            } else {
                map.put("provinceNo", sendLocation.get().getProvinceNo());
            }
        }

        if (null != sendLocation.get()) {
            if (TextUtils.isEmpty(sendLocation.get().getCityNo())) {
                map.put("cityNo", "");
            } else {
                map.put("cityNo", sendLocation.get().getCityNo());
            }
        }
        if (null != sendLocation.get()) {
            if (TextUtils.isEmpty(sendLocation.get().getAreaNo())) {
                map.put("districtNo", "");
            } else {
                map.put("districtNo", sendLocation.get().getAreaNo());
            }
        }
        if (null != purposeLocation.get()) {
            if (TextUtils.isEmpty(purposeLocation.get().getProvinceNo())) {
                map.put("destProvinceNo", "");
            } else {
                map.put("destProvinceNo", purposeLocation.get().getProvinceNo());
            }
        }

        if (null != purposeLocation.get()) {
            if (TextUtils.isEmpty(purposeLocation.get().getCityNo())) {
                map.put("destCityNo", "");
            } else {
                map.put("destCityNo", purposeLocation.get().getCityNo());
            }
        }
        if (null != purposeLocation.get()) {
            if (TextUtils.isEmpty(purposeLocation.get().getAreaNo())) {
                map.put("destDistrictNo", "");
            } else {
                map.put("destDistrictNo", purposeLocation.get().getAreaNo());
            }
        }

        if (null != carLength.get()) {
            map.put("carLenNo", carLength.get().getNo());
        }

        if (!TextUtils.isEmpty(carType.get().getNo())) {
            map.put("carTypeNo", carType.get().getNo());
        }

        if (TextUtils.isEmpty(filterEntity.get().getNeedVideo())) {
            map.put("needVideo", "0");
        } else {
            map.put("needVideo", filterEntity.get().getNeedVideo());
        }

        map.put("keyWord", keyWord);

        if (findGoodsType.get() != null && !TextUtils.isEmpty(findGoodsType.get().getNo())) {
            map.put("carrierType", Integer.parseInt(findGoodsType.get().getNo()));
        } else {
            map.put("carrierType", "");
        }

        DialogHelper.showProgressDialog(fragment.getContext(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        NewAPIManager.getInstance().getLogisticsAPI().getListCarFindForGoods(map)
                .enqueue(new Callback<BaseEntity<ProListEntity<List<CarriageInfo>>>>() {
                    @Override
                    public void onResponse(Call<BaseEntity<ProListEntity<List<CarriageInfo>>>> call, Response<BaseEntity<ProListEntity<List<CarriageInfo>>>> response) {
                        DialogHelper.dismissProgressDialog();
                        if (response.body() == null)
                            return;
                        if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                            if (response.body().getData() == null || response.body().getData().getList() == null) {
                                MToast.showToast(fragment.getActivity(), "暂无数据");
                            } else
                                fragment.getCarrierInfoData(response.body().getData().getList());
                        } else {
                            fragment.getCarrierInfoData(new ArrayList<>());
                            MToast.showToast(fragment.getActivity(), response.message());
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseEntity<ProListEntity<List<CarriageInfo>>>> call, Throwable t) {
                        DialogHelper.dismissProgressDialog();
                        t.printStackTrace();
                        MToast.showToast(fragment.getActivity(), t.getMessage());
                    }
                });
    }

    /**
     * 获取地图页承运列表数据
     */
    public void getMapCar(String keyWord) {
        Map map = new HashMap();
        map.put("page", 1);
        map.put("limit", 50);

        //当前地图半径
        if (!TextUtils.isEmpty(radius)) {
            map.put("radius", radius);
        }

        if (LocationUtil.isOpenLocation(fragment.getActivity()) && LocationUtil.currentLocationIsValid()) {
            map.put("longitude", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, ""));
            map.put("latitude", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, ""));
        } else {
            // TODO: 2021/12/15 没开启定位逻辑处理
        }

        if (null != sendLocation.get()) {
            if (TextUtils.isEmpty(sendLocation.get().getProvinceNo())) {
                map.put("provinceNo", "");
            } else {
                map.put("provinceNo", sendLocation.get().getProvinceNo());
            }
            if (TextUtils.isEmpty(sendLocation.get().getCityNo())) {
                map.put("cityNo", "");
            } else {
                map.put("cityNo", sendLocation.get().getCityNo());
            }
            if (TextUtils.isEmpty(sendLocation.get().getAreaNo())) {
                map.put("districtNo", "");
            } else {
                map.put("districtNo", sendLocation.get().getAreaNo());
            }
        }
        if (null != purposeLocation.get()) {
            if (TextUtils.isEmpty(purposeLocation.get().getProvinceNo())) {
                map.put("destProvinceNo", "");
            } else {
                map.put("destProvinceNo", purposeLocation.get().getProvinceNo());
            }

            if (TextUtils.isEmpty(purposeLocation.get().getCityNo())) {
                map.put("destCityNo", "");
            } else {
                map.put("destCityNo", purposeLocation.get().getCityNo());
            }
            if (TextUtils.isEmpty(purposeLocation.get().getAreaNo())) {
                map.put("destDistrictNo", "");
            } else {
                map.put("destDistrictNo", purposeLocation.get().getAreaNo());
            }
        }

        if (null != carLength.get()) {
            map.put("carLenNo", carLength.get().getNo());
        }

        if (!TextUtils.isEmpty(carType.get().getNo())) {
            map.put("carTypeNo", carType.get().getNo());
        }

        if (TextUtils.isEmpty(filterEntity.get().getNeedVideo())) {
            map.put("needVideo", "0");
        } else {
            map.put("needVideo", filterEntity.get().getNeedVideo());
        }

        map.put("keyWord", keyWord);

        if (findGoodsType.get() != null && !TextUtils.isEmpty(findGoodsType.get().getNo())) {
            map.put("carrierType", Integer.parseInt(findGoodsType.get().getNo()));
        } else {
            map.put("carrierType", "");
        }

        DialogHelper.showProgressDialog(fragment.getContext(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        NewAPIManager.getInstance().getLogisticsAPI().getMapCarFindForGoods(map)
                .enqueue(new Callback<BaseEntity<ProListEntity<List<MapCarEntity>>>>() {
                    @Override
                    public void onResponse(Call<BaseEntity<ProListEntity<List<MapCarEntity>>>> call, Response<BaseEntity<ProListEntity<List<MapCarEntity>>>> response) {
                        DialogHelper.dismissProgressDialog();
                        if (response.body() == null)
                            return;
                        if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                            if (response.body().getData() == null || response.body().getData().getList() == null) {
                                MToast.showToast(fragment.getContext(), "没有更多数据了");
                            } else {
                                ldCars.postValue(response.body().getData().getList());
                            }
                        } else {
                            MToast.showToast(fragment.getActivity(), response.message());
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseEntity<ProListEntity<List<MapCarEntity>>>> call, Throwable t) {
                        DialogHelper.dismissProgressDialog();
                        if (!TextUtils.isEmpty(t.getMessage()))
                            MToast.showToast(fragment.getActivity(), t.getMessage());

                    }
                });
    }

    public void getAddressModel() {
        if (fragment.getActivity() == null) {
            return;
        }
        AddressHelper.getInstance().getAllArea(new AddressHelper.CallBack() {
            @Override
            public void initialData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
                if (data != null && data.size() > 0) {
                    fragment.initAddressData(data);
                }
            }

            @Override
            public void threeData(List<AddressEntity> provinceList, List<List<AddressEntity>> cityList, List<List<List<AddressEntity>>> districtList) {
            }
        });
    }

    //根据城市区域查询经纬度
    public void getLocation(Context context, String cityName, String areaName) {
        if (TextUtils.isEmpty(cityName) || cityName.equals("不限")) {
            cityName = sendLocation.get().getProvinceName();
        }
        GeocodeSearch geocodeSearch = new GeocodeSearch(context);
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int code) {

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int code) {
                if (code != 1000) return;
                if (geocodeResult != null && geocodeResult.getGeocodeAddressList() != null &&
                        geocodeResult.getGeocodeAddressList().size() > 0) {
                    GeocodeAddress geocodeAddress = geocodeResult.getGeocodeAddressList().get(0);
                    double latitude = geocodeAddress.getLatLonPoint().getLatitude();//纬度
                    double longitude = geocodeAddress.getLatLonPoint().getLongitude();//经度
                    //回调UI
                    ldLatLng.postValue(new LatLng(latitude, longitude));
                } else {
                    MToast.showToast(getApplication(), "地址名出错");
                }
            }
        });
        GeocodeQuery geocodeQuery = new GeocodeQuery(cityName + areaName, cityName);
        geocodeSearch.getFromLocationNameAsyn(geocodeQuery);
    }

    /**
     * 获取车辆类型
     */
    public void getCarTypeList() {
        if (fragment.getActivity() == null) {
            return;
        }

        NewAPIManager.getInstance().getLogisticsAPI().getCarTypeAndLen("").enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
                List<GoodsInfoTypeEntity3> carTypeList = data.getData() != null ? data.getData() : new ArrayList<>();
                List<GoodsInfoTypeEntity3> carLenList = new ArrayList<>();
                //添加全部车长数据
                for (GoodsInfoTypeEntity3 carType : carTypeList) {
                    if (carType.getCarLenList() == null) continue;
                    carLenList.addAll(carType.getCarLenList());
                }
                //添加车型不限时所有车长数据
                GoodsInfoTypeEntity3 type = new GoodsInfoTypeEntity3("", "不限");
                type.setCarLenList(carLenList);
                carTypeList.add(0, type);
                //添加子列表不限车长
                for (GoodsInfoTypeEntity3 carType : carTypeList) {
                    if (carType.getCarLenList() == null) {
                        carType.setCarLenList(new ArrayList<>());
                    }
                    GoodsInfoTypeEntity3 len = new GoodsInfoTypeEntity3("", "不限");
                    carType.getCarLenList().add(0, len);
                }
                //刷新车长与车型
                fragment.getCarsTypeData(carTypeList);
                fragment.getCarsLengthData(carLenList);
            }
        });
    }


}
